# project
cmake_minimum_required(VERSION 3.13.0)
project(shared_memory VERSION 1.2.1 LANGUAGES C CXX ASM)


option(BUILD_TESTING "" ON)

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)

# target
add_library(shared_memory STATIC "")
set_target_properties(shared_memory PROPERTIES OUTPUT_NAME "shared_memory")
target_compile_options(shared_memory PRIVATE -fPIC)
target_include_directories(shared_memory PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<INSTALL_INTERFACE:include/shm_kernel>
)
if (LINUX OR UNIX OR MACOS)
    target_compile_definitions(shared_memory PUBLIC
        USE_POSIX_SHM
    )
    target_sources(shared_memory PRIVATE
        src/posix_impl.cxx
    )
    target_link_libraries(shared_memory PRIVATE 
        rt
    )
    set(TESTCASE_SRC tests/Testcase_posix.cxx)
elseif (WIN32)
    target_compile_definitions(shared_memory PUBLIC 
        USE_WIN32_SHM
    )
    target_sources(shared_memory PRIVATE 
        src/win32_impl.cxx
    )
    set(TESTCASE_SRC tests/Testcase_win32.cxx)
endif()
target_compile_features(shared_memory PUBLIC cxx_std_17)
set_target_properties(shared_memory PROPERTIES 
                        PUBLIC_HEADER 
                            "${CMAKE_CURRENT_SOURCE_DIR}/include/shmhdl.hpp")


# build testcase
if(BUILD_TESTING)
    find_package(Catch2 REQUIRED)
    enable_testing()
    add_executable(Testcase ${TESTCASE_SRC})
    target_link_libraries(Testcase PRIVATE Catch2::Catch2WithMain shared_memory)
    add_test(NAME testcase COMMAND ./Testcase
        WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/bin
    )
endif()


# install headers, libs and export targets
include(CMakePackageConfigHelpers)
configure_package_config_file(
    "${CMAKE_CURRENT_SOURCE_DIR}/cmake/config.cmake.in"
    "shared_memoryConfig.cmake"
    INSTALL_DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/cmake/shared_memory"

)
write_basic_package_version_file(
    "shared_memoryConfigVersion.cmake"
    VERSION ${PROJECT_VERSION}
    COMPATIBILITY SameMajorVersion
)

install(TARGETS shared_memory 
        EXPORT shared_memory
        LIBRARY DESTINATION lib
        ARCHIVE DESTINATION lib
        RUNTIME DESTINATION bin
        PUBLIC_HEADER DESTINATION include/shm_kernel
        )

install(
    EXPORT shared_memory
    FILE "shared_memoryTargets.cmake"
    NAMESPACE shm_kernel::
    DESTINATION "lib/cmake/shared_memory"
)
install(FILES 
            "${CMAKE_CURRENT_BINARY_DIR}/shared_memoryConfig.cmake"
            "${CMAKE_CURRENT_BINARY_DIR}/shared_memoryConfigVersion.cmake"
        DESTINATION 
            lib/cmake/shared_memory
        )